#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "Cnbot-Work";
const char* pwd = "Cnbot001";
const char* mqtt_server = "47.107.230.32";

WiFiClient mWifiClient;
PubSubClient mqttClient(mWifiClient);

long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi(){
    delay(10);
    Serial.println();
    Serial.print("Connecting to");
    Serial.print(ssid);

    WiFi.begin(ssid, pwd);
    while (WiFi.status() != WL_CONNECTED){
        delay(500);
        Serial.print(".");
    }
    randomSeed(micros());
    Serial.println("");
    Serial.println("Wifi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void mqtt_msg_callback(char* topic, byte* payload, unsigned int len){
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("]");
    for (int i = 0; i < len; ++i) {
        Serial.print((char)payload[i]);
    }
    Serial.println();
    if(len > 0){
        char ctl = (char)payload[0];
        if(ctl == '1'){
            digitalWrite(LED_BUILTIN, LOW);
        }else{
            digitalWrite(LED_BUILTIN, HIGH);
        }
    }
}

const char* mqtt_user = "admin";
const char* mqtt_pwd = "ytf99";

void reconnect(){
    while (!mqttClient.connected()){
        Serial.print("Attemping MQTT connection...");
        String clientId = "ESP8266Client-";
        clientId += String(random(0xffff), HEX);
        if(mqttClient.connect(clientId.c_str(),mqtt_user, mqtt_pwd)){
            Serial.println("mqtt connected");
            mqttClient.publish("outTopic", "1");
            mqttClient.subscribe("inTopic");
        }else{
            Serial.print("failed, rc=");
            Serial.print(mqttClient.state());
            Serial.println(" try again in 3 seconds");
            delay(3000);
        }
    }
}

void setup() {
// write your initialization code here
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.begin(9600);
    setup_wifi();
    mqttClient.setServer(mqtt_server, 1883);
    mqttClient.setCallback(mqtt_msg_callback);
    digitalWrite(LED_BUILTIN, HIGH);
}

void loop() {
// write your code here
    if(!mqttClient.connected()){
        reconnect();
    }
    mqttClient.loop();
    unsigned long now = millis();
    if(now - lastMsg > 2000){
        lastMsg = now;
        ++value;
        snprintf(msg, 50, "hello world #%ld, led state:%d", value, digitalRead(LED_BUILTIN));
        Serial.print("Publish message: ");
        Serial.print(msg);
        mqttClient.publish("outTopic", msg);
    }
}